package it.trekker.map;

import it.trekker.R;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;


public class PathOverlayManager {

	private List<Overlay> mapOverlays = null;
	private GeoPoint lastPoint = null; 
	private Projection projection = null; 
	
	private Drawable markerStart;
	private MyItemizedOverlay startItemizedOverlay;
	
	private Drawable markerStop;
	private MyItemizedOverlay stopItemizedOverlay;
	

	public PathOverlayManager(Context ctx, List<Overlay> mapOverlays, Projection mapProjection) {
		this.mapOverlays = mapOverlays;
		projection = mapProjection;
		
		markerStart = ctx.getResources().getDrawable(R.drawable.route_start_icon);
		startItemizedOverlay = new MyItemizedOverlay(markerStart);
//		mapOverlays.add(startItemizedOverlay);
		
		markerStop = ctx.getResources().getDrawable(R.drawable.route_stop_icon);
		stopItemizedOverlay = new MyItemizedOverlay(markerStop);
//		mapOverlays.add(stopItemizedOverlay);
	}   

	public void addPoint(GeoPoint p) {

		if(lastPoint != null) {
			PathOverlay pathOverlay = new PathOverlay(lastPoint, p); 
			mapOverlays.add(pathOverlay);
		}
		else {
			startItemizedOverlay.addItem(p, "Start", "Start");
		}

		lastPoint = p;
	}
	
	public void endPath() {
		if(lastPoint != null) {
			stopItemizedOverlay.addItem(lastPoint, "Stop", "Stop");
			mapOverlays.add(startItemizedOverlay);
			mapOverlays.add(stopItemizedOverlay);
		}
	}
	
	
	
	
	//*********************************************//
	//*************** Overlay class ***************//
	//*********************************************//
	
	
	private class PathOverlay extends Overlay {
		
		private GeoPoint from = null;
		private GeoPoint to = null;
		
		public PathOverlay(GeoPoint from, GeoPoint to) {
			this.from = from;
			this.to = to;
		}  
		
		@Override
		public void draw(Canvas canvas, MapView mapv, boolean shadow){
			super.draw(canvas, mapv, shadow);
			
			if(from != null && to != null) {
				Paint mPaint = new Paint();
				mPaint.setDither(true);
				mPaint.setColor(Color.RED);
				mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
				mPaint.setStrokeJoin(Paint.Join.ROUND);
				mPaint.setStrokeCap(Paint.Cap.ROUND);
				mPaint.setStrokeWidth(2);
				
				Point p1 = new Point();
				Point p2 = new Point();
				Path path = new Path();
				
				projection.toPixels(from, p1);
				projection.toPixels(to, p2);
				
				path.moveTo(p2.x, p2.y);
				path.lineTo(p1.x,p1.y);
				
				canvas.drawPath(path, mPaint);
			}
		}
	}
}



